﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Framework;
using myBoard.Radio.BO;
using System.Windows.Threading;
using System.Reflection;

namespace myBoard.Radio
{
    public partial class Radio : UserControl , IMagnet , IRequiresStorage
    {
        private Storage _storage;
        MediaElement _mediaElement;
        RadioStations _stations;
        private int _currentStationIndex = 0;
        DispatcherTimer _bufferingCheckerTimer;
        Settings _settings;
        DispatcherTimer _dateTimeUpdater;

        public Radio()
        {
            InitializeComponent();
            _frontFlipButton.Click += new RoutedEventHandler(_frontFlipButton_Click);
            _saveBt.Click += new RoutedEventHandler(_saveBt_Click);
            _mediaElement = new MediaElement();
            _mediaElement.LoadedBehavior = MediaState.Manual;
            _mediaElement.UnloadedBehavior = MediaState.Manual;
            _mediaElement.BufferingStarted += new RoutedEventHandler(_mediaElement_BufferingStarted);
            _mediaElement.BufferingEnded += new RoutedEventHandler(_mediaElement_BufferingEnded);
            
            _stations = new RadioStations();
            _nextStationBt.Click += new RoutedEventHandler(_nextStationBt_Click);
            _previousStationBt.Click += new RoutedEventHandler(_previousStationBt_Click);
            _playPauseBt.Click += new RoutedEventHandler(_playPauseBt_Click);
            _bufferingCheckerTimer = new DispatcherTimer();
            _bufferingCheckerTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            _bufferingCheckerTimer.Tick += new EventHandler(bufferingCheckerTimer_Tick);
            _addStation.Click+=new RoutedEventHandler(_addStation_Click);
            _deleteStations.Click += new RoutedEventHandler(_deleteStations_Click);

            _dateTimeUpdater = new DispatcherTimer();
            _dateTimeUpdater.Interval = new TimeSpan(0, 1, 0);
            _dateTimeUpdater.Tick += new EventHandler(_dateTimeUpdater_Tick);
            this.Loaded += new RoutedEventHandler(Radio_Loaded);
        }

        void Radio_Loaded(object sender, RoutedEventArgs e)
        {
            _dateTimeUpdater.Start();
            _dateTimeUpdater_Tick(null, null);
            _stationName.Content = _stations[_currentStationIndex].Name;    
        }

        void _dateTimeUpdater_Tick(object sender, EventArgs e)
        {
            _time.Content = DateTime.Now.ToShortTimeString();
            string day = DateTime.Now.ToLongDateString();
            day = day[0].ToString().ToUpper()+day.Substring(1,day.Length-1);
            _day.Content = day;            
        }

        void _deleteStations_Click(object sender, RoutedEventArgs e)
        {
            string streamUrl = ((RadioStation)_stationsList.SelectedItem).StreamUrl;
            for(int i = 0 ; i< _stations.Count;i++)
            {
                if (_stations[i].StreamUrl == streamUrl)
                {
                    _stations.RemoveAt(i);
                    break;
                }
            }

            _stationsList.Items.Remove(_stationsList.SelectedItem);
        }

        void _addStation_Click(object sender, RoutedEventArgs e)
        {
            RadioStation station = new RadioStation() { Name = _newStationName.Text, StreamUrl = _newStationUrl.Text };
            _stations.Add(station);
            _stationsList.Items.Add(station);
        }

        void _saveBt_Click(object sender, RoutedEventArgs e)
        {
            if (FlipRequested != null)
                FlipRequested(MagnetSides.Front);
        }

        void _frontFlipButton_Click(object sender, RoutedEventArgs e)
        {
            if (FlipRequested != null)
                FlipRequested(MagnetSides.Back);
        }

        void bufferingCheckerTimer_Tick(object sender, EventArgs e)
        {
            if (_mediaElement.IsBuffering)
                _bufferingLabel.Content = string.Format("Buffering {0} %", Convert.ToInt16(_mediaElement.BufferingProgress*100));
            else
                _bufferingLabel.Content = string.Empty;
        }

        void _mediaElement_BufferingEnded(object sender, RoutedEventArgs e)
        {
            _bufferingLabel.Content = string.Empty;
        }

        void _mediaElement_BufferingStarted(object sender, RoutedEventArgs e)
        {
            _bufferingCheckerTimer.Start();
        }

        void _previousStationBt_Click(object sender, RoutedEventArgs e)
        {
            if (_currentStationIndex > 0)
                _currentStationIndex--;
            else
                _currentStationIndex = _stations.Count-1;

            _mediaElement.Source = new Uri(_stations[_currentStationIndex].StreamUrl);
            _mediaElement.Play();
            _stationName.Content = _stations[_currentStationIndex].Name;  
        }

        void _nextStationBt_Click(object sender, RoutedEventArgs e)
        {
            if(_currentStationIndex<_stations.Count-1)
                _currentStationIndex++;
            else
                _currentStationIndex=0;

            _mediaElement.Source = new Uri(_stations[_currentStationIndex].StreamUrl);
            _mediaElement.Play();
            _stationName.Content = _stations[_currentStationIndex].Name;  
        }

        bool _playing = false;

        void _playPauseBt_Click(object sender, RoutedEventArgs e)
        {
            if (_playing)
                _mediaElement.Stop();
            else
            {
                _mediaElement = new MediaElement();
                _mediaElement.LoadedBehavior = MediaState.Manual;
                _mediaElement.UnloadedBehavior = MediaState.Manual;
                _mediaElement.BufferingStarted += new RoutedEventHandler(_mediaElement_BufferingStarted);
                _mediaElement.BufferingEnded += new RoutedEventHandler(_mediaElement_BufferingEnded);

                _mediaElement.Source = new Uri(_stations[_currentStationIndex].StreamUrl);                
                _stationName.Content = _stations[_currentStationIndex].Name; 
                _mediaElement.Play();
            }

            _playing = !_playing;            
        }

        #region IMagnet Members

        public event OnFlipRequested FlipRequested;

        public event EventHandler CloseMyBoardRequested;

        public string MagnetName
        {
            get { return "Radio"; }
        }

        public BitmapImage Icon
        {
            get
            {
                return ResourcesAccess.GetBitmapImageFromResource(Assembly.GetExecutingAssembly(), "myBoard.Radio.Images.Icon.png");
            }
        }

        BitmapImage _thumbnail;

        public BitmapImage Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                {
                    _thumbnail = Tools.GetBitmapImageFromFrameworkElement(this);
                }
                return _thumbnail;
            }
        }

        public Panel GetFrontSide()
        {
            return _frontSide;
        }

        public Panel GetBackSide()
        {
            return _backSide;
        }

        public Panel GetFlipZone()
        {
            return _flipZone;
        }

        public void Terminate()
        {
            SaveState();

            if (_playing)
            {
                _bufferingCheckerTimer.Stop();
                _bufferingCheckerTimer = null;
                _mediaElement.Stop();
                _mediaElement = null;
            }
        }

        #endregion

        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            _storage = storage;
            _settings = Serialization.DeSerialize(System.IO.Path.Combine(_storage.StorageDirectory.FullName,"Settings.xml"));
            _stations = _settings.UserRationStations;
            if (_stations.Count == 0)
            {
                RadioStation radio1 = new RadioStation() { Name = "RTL", StreamUrl = "http://streaming.radio.rtl.fr/rtl-1-44-96", WebSite = "http://www.rtl.fr/" };
                RadioStation radio2 = new RadioStation() { Name = "Europe1", StreamUrl = "http://live.europe1.fr/V4/europe1/europe1.asx", WebSite = "http://europe1.fr" };
                RadioStation radio3 = new RadioStation() { Name = "HOT 108", StreamUrl = "http://scfire-ntc-aa04.stream.aol.com:80/stream/1030", WebSite = "http://www.skyrock.com/" };
                _stations.Add(radio3); 
                _stations.Add(radio1);
                _stations.Add(radio2);
                
            }

            foreach(RadioStation radio in _stations)
            {
                RadioStation station = new RadioStation() { Name = radio.Name, StreamUrl = radio.StreamUrl };
                _stationsList.Items.Add(station);
            }
        }

        public void SaveState()
        {
            _settings.UserRationStations = _stations;
            Serialization.Serialize(_settings, System.IO.Path.Combine(_storage.StorageDirectory.FullName, "Settings.xml"));
        }

        #endregion
    }
}
